﻿Imports System.Drawing

Public Class DrawTextHelper
  Public Shared Sub DrawText(ByVal gra As Graphics, ByVal textToAdd As String, _
   ByVal width As Single, ByVal height As Single, ByVal textFont As Font, ByVal textOpacity As Integer, _
   ByVal textColor As System.Drawing.Color)

    If gra Is Nothing Then
      Return
    End If

    Dim the_font As Font
    Dim string_format As New StringFormat
    Dim layout_rect As RectangleF
    Dim brush1 As Brush

    gra.SmoothingMode = Drawing2D.SmoothingMode.HighQuality

    string_format.Alignment = StringAlignment.Center
    string_format.FormatFlags = StringFormatFlags.LineLimit
    string_format.Trimming = StringTrimming.Word

    ' Get the font.
    the_font = textFont

    brush1 = New SolidBrush(Color.FromArgb(textOpacity, textColor))

    ' Get the area available for this paragraph.
    layout_rect = New RectangleF(0, 0, width, height)

    ' Draw the text.
    gra.DrawString(textToAdd, the_font, brush1, layout_rect, string_format)

    'the_font.Dispose()
    brush1.Dispose()
    string_format.Dispose()

  End Sub

  Public Shared Function DrawText(ByVal imagePath As String, ByVal textToAdd As String) As String

    Dim text = New FormattedText(textToAdd, _
                                 New System.Globalization.CultureInfo("en-us"), FlowDirection.LeftToRight, _
                                 New System.Windows.Media.Typeface("Calibri"), _
                                18, System.Windows.Media.Brushes.Blue)

    Dim image = New BitmapImage
    image.BeginInit()
    image.CacheOption = BitmapCacheOption.OnLoad
    image.UriSource = New Uri(imagePath)
    image.EndInit()

    Dim drawingVisual = New DrawingVisual()

    Dim drawingContext = drawingVisual.RenderOpen()

    drawingContext.DrawImage(image, New Rect(0, 0, image.Width, image.Height))
    'drawingContext.DrawText(text, New System.Windows.Point(image.Height / 2, 0))
    drawingContext.DrawText(text, New System.Windows.Point(image.Width / 2, 0))
    drawingContext.Close()

    Dim renderBmap = New RenderTargetBitmap(image.PixelWidth, image.PixelHeight, image.DpiX, image.DpiY, PixelFormats.Pbgra32)
    renderBmap.Render(drawingVisual)

    Dim png = New PngBitmapEncoder()

    png.Frames.Add(BitmapFrame.Create(renderBmap))
    Using stm As IO.Stream = IO.File.Create(imagePath & ".PostExt.PNG")
      png.Save(stm)
    End Using

    Return imagePath & ".PostExt.PNG"
  End Function

End Class
